<template>
  <div class="info-page">
    <div class="info-header">
      <div class="left">
        <img src="@/assets/image/form/header-info.png" alt="">
        任务详情
      </div>
      <div class="right">
        <el-button type="success" :icon="Select" @click="sunmitTask">提交</el-button>
        <el-button :icon="Promotion" @click="goBackLast">返回</el-button>
      </div>
    </div>
    <div class="info-detail">
      <el-scrollbar style="height:100%">
        <div class="detail-header">
          任务信息
        </div>
        <el-form ref="infoFormRef" :model="infoRuleForm" :rules="infoRules" label-width="150px" class="el-row">
          <el-form-item label="任务名称：" prop="name" class="el-col el-col-23">
            <el-input v-model="infoRuleForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="创建人：" prop="createHumanName" class="el-col el-col-11">
            <el-input v-model="infoRuleForm.createHumanName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="所属行业：" prop="industryName" class="el-col el-col-11 el-col-offset-1">
            <el-select v-model="infoRuleForm.industryName" style="width: 100%;" clearable>
              <el-option v-for="(option,index) in reactiveData.industryList" @click.native="changeIndustry(option)" :key="index" :label="option.name" :value="option.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务专题：" prop="taskSubject" class="el-col el-col-11">
            <el-autocomplete style="width:100%" clearable class="inline-input" v-model="infoRuleForm.taskSubject" :fetch-suggestions="querySearch" placeholder="请输入任务专题"></el-autocomplete>
          </el-form-item>
          <el-form-item label="任务类型：" prop="taskTypeName" class="el-col el-col-11 el-col-offset-1">
            <el-select v-model="infoRuleForm.taskTypeName" style="width: 100%;" clearable>
              <el-option v-for="(option,index) in reactiveData.taskTypeList" @click.native="changeTaskType(option)" :key="index" :label="option.name" :value="option.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否是周期性任务：" prop="isCircle" class="el-col el-col-11">
            <el-select v-model="infoRuleForm.isCircle" style="width: 100%;">
              <el-option v-for="(option,index) in statusType" :key="index" :label="option.name" :value="option.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务状态" prop="statusName" class="el-col el-col-11 el-col-offset-1" v-show="id">
            <el-select v-model="infoRuleForm.statusName" allow-create filterable placeholder="请选择任务状态" style="width:100%">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.label" @click.native="changeStatusName(infoRuleForm,item)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="期望执行时间：" prop="arrTime" class="el-col el-col-23">
            <el-date-picker clearable v-model="infoRuleForm.arrTime" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item label="数据类型" class="el-col el-col-23">
            <el-button type="primary" style="margin-bottom:1rem;" @click="addTableOne">新增</el-button>
            <el-table :data="reactiveData.dataTypeTable" stripe :header-cell-style="{
              'font-size': '1rem',
              'height':'3rem',
              'background': '#E5EBF3 !important',
              'color': '#333333',
            }">
              <el-table-column type="index" width="60" label="序号" />
              <el-table-column label="类型">
                <template #default="scope">
                  <el-select v-model="scope.row.typeName" style="width: 100%;" clearable>
                    <el-option v-for="(option,index) in reactiveData.dataType" :key="index" :label="option.name" :value="option.name" @click.native="changeTypeData(option,scope.$index,scope.row)"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="精度/分辨率">
                <template #default="scope">
                  <el-select v-model="scope.row.accuracy" style="width: 100%;" clearable>
                    <el-option v-for="(option,index) in scope.row.accuracyList" :key="index" :label="option.name" :value="option.code"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button @click="deleteDataType(scope.$index)" type="danger">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="备注:" prop="comment" class="el-col el-col-23">
            <el-input style="width: 100%;" v-model="infoRuleForm.comment" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-form>


        <div class="detail-header">
          测区信息
        </div>

        <div class="area-group">
          <el-button type="primary" style="margin-bottom:1rem;" @click="addAreaOne">新增测区</el-button>
          <div class="area-item" v-for="(option,index) in reactiveData.areaList" :key="index">
            <div class="area-handle">
              <div class="area-label">测区{{index+1}}</div>
              <el-button type="danger" v-if="index>0" @click="deleteAreaOne(index)">删除</el-button>
            </div>
            <el-form :ref="`area${index}`" :model="option" :rules="areaRules" label-width="150px" class="el-row">
              <el-form-item label="测区名称：" prop="name" class="el-col el-col-11">
                <el-input v-model="option.name" placeholder="请填写测区名称"></el-input>
              </el-form-item>
              <el-form-item label="所属区县：" prop="regionName" class="el-col el-col-11 el-col-offset-1">
                <el-select v-model="option.regionName" style="width: 100%;" clearable>
                  <el-option v-for="(option,i) in reactiveData.areaBelongList" @click.native="changeRegion(option,index)" :key="i" :label="option.name" :value="option.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="测区地址：" prop="address" class="el-col el-col-23">
                <el-input v-model="option.address" placeholder="请输入测区地址"></el-input>
              </el-form-item>
              <el-form-item label="测区范围：" class="el-col el-col-11">
                <el-upload v-model:file-list="option.areaFileList" action="" multiple :before-upload="beforeUpload" :on-remove="handleRemove">
                  <el-button type="primary" @click="setUpload(index)">点击上传</el-button>
                  <span style="margin-left: 1rem;color: #606266;"> 支持kml。</span>
                </el-upload>
              </el-form-item>
              <el-form-item label="测区面积（km²）：" prop="area" class="el-col el-col-11 el-col-offset-1">
                <el-input v-model="option.area" placeholder="请输入测区面积"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang=ts>
import { ref, reactive } from "vue";
import { Select, Promotion } from "@element-plus/icons-vue";
import type { FormRules, FormInstance, UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import {
  industryBelong,
  gethistorysubject,
  taskType,
  areaRegion,
  uploadFIleSurveyedArea,
  createTaskInfo,
  getUavTaskPageList,
  editTaskInfo,
} from "@/api/task";
import { useRoute } from "vue-router";
import { recoverData } from "@/utils/util";
import router from "@/router";

interface statusTypeInerface {
  name: string;
  value: string;
}

const infoFormRef = ref<FormInstance>();

let id = ref("");
let uploadIndex = ref(-1);

const statusOptions: any[] = reactive([
  {
    label: "进行中",
    value: "executing",
  },
  {
    label: "已完成",
    value: "over",
  },
]);

let infoRuleForm = reactive({
  name: "",
  createHumanName: "admin",
  industryName: "",
  industryCode: "",
  taskSubject: "",
  taskTypeName: "",
  taskTypeCode: "",
  isCircle: "0",
  arrTime: Array<string>(),
  comment: "",
  taskUse: "",
  statusName: "",
  temporaryData: {},
});

//会变的reactive变量
let reactiveData: any = reactive({
  editObj: {},
  industryList: [],
  restaurants: [],
  taskTypeList: [],
  dataTypeTable: [
    {
      type: "",
      typeCode: "",
      typeName: "",
      accuracy: "",
    },
  ],
  dataType: [],
  accuracyList: [],
  areaList: [
    {
      name: "",
      regionName: "",
      regionCode: "",
      address: "",
      area: "",
      areaFileList: [],
      attachFile: "",
    },
  ],
  areaBelongList: [],
});

const infoRules = reactive<FormRules>({
  name: [{ required: true, message: "请输入任务名称" }],
  industryName: [{ required: true, message: "请选择所属行业" }],
  taskSubject: [{ required: true, message: "请输入任务专题" }],
  taskTypeName: [{ required: true, message: "请选择任务类型：" }],
  arrTime: [{ required: true, message: "请选择期望执行时间：" }],
});

const areaRules = reactive<FormRules>({
  name: [{ required: true, message: "请输入测区名称" }],
  regionName: [{ required: true, message: "请选择所属区县" }],
  address: [{ required: true, message: "请输入测区地址" }],
  area: [{ required: true, message: "请填写测区面积" }],
});

const statusType: Array<statusTypeInerface> = reactive([
  {
    name: "是",
    value: "1",
  },
  {
    name: "否",
    value: "0",
  },
]);

const getData = async (id: string) => {
  const req = {
    objCondition: {
      id,
    },
    orderby: "statusName_desc,startTime_desc",
    pageIndex: 1,
    pageSize: 10,
  };
  const res: any = await getUavTaskPageList(req);
  if (res.statusCode === 200) {
    reactiveData.editObj = res.data.dataSource[0];
    infoRuleForm.arrTime[0] = reactiveData.editObj.startTime;
    infoRuleForm.arrTime[1] = reactiveData.editObj.endTime;

    recoverData(infoRuleForm, reactiveData.editObj);
    reactiveData.dataTypeTable = reactiveData.editObj.tbDataTypeInfoList;
    reactiveData.areaList = reactiveData.editObj.tbSurveyInfoList;
    console.log(reactiveData.areaList, reactiveData.editObj.tbSurveyInfoList);

    reactiveData.areaList.forEach((item: any) => {
      item.areaFileList = [];
      let arr = item.attachFile.split(",");
      arr.forEach((obj: any) => {
        if (obj) {
          item.areaFileList.push({
            name: obj,
            type: "success",
          });
        }
      });
    });
  } else {
  }
};

const route = useRoute();

const changeStatusName = (data: any, obj: any) => {
  data.statusCode = obj.value;
};

const sunmitTask = async () => {
  let startTime = infoRuleForm.arrTime[0];
  let endTime = infoRuleForm.arrTime[1];
  let req = {
    ...infoRuleForm,
    startTime,
    endTime,
    tbDataTypeInfoList: reactiveData.dataTypeTable,
    tbSurveyInfoList: reactiveData.areaList,
  };

  if (id.value) {
    recoverData(reactiveData.editObj, req);
  }

  const res: any = id.value
    ? await editTaskInfo(reactiveData.editObj)
    : await createTaskInfo(req);
  if (res.statusCode === 200) {
    ElMessage({
      message: `${id ? "编辑" : "新增"}任务成功`,
      type: "success",
    });
    goBackLast();
  } else {
  }
};

const goBackLast = () => {
  router.push({
    path: "/home/task/dataAcquisition",
  });
};

const changeIndustry = (val: any) => {
  infoRuleForm.industryCode = val.code;
};

const changeTaskType = (val: any) => {
  infoRuleForm.taskTypeCode = val.code;
};

const changeRegion = (val: any, index: number) => {
  reactiveData.areaList[index].regionCode = val.code;
};

//上传测区
const setUpload = (index: number) => {
  uploadIndex.value = index;
};

const beforeUpload: UploadProps["beforeUpload"] = async (file) => {
  if (file.name.substring(file.name.lastIndexOf(".")) !== ".kml") {
    ElMessage({
      message: `仅限上传kml文件`,
      type: "warning",
    });
    return false;
  }
  let formData = new FormData();
  formData.append("file", file);
  const res: any = await uploadFIleSurveyedArea(formData);
  if (res.statusCode === 200) {
    reactiveData.areaList[uploadIndex.value].areaFileList.push({
      name: res.data,
      status: "success",
    });
    reactiveData.areaList[uploadIndex.value].attachFile = reactiveData.areaList[
      uploadIndex.value
    ].attachFile
      ? `${reactiveData.areaList[uploadIndex.value].attachFile},${res.data}`
      : res.data;
    ElMessage({
      message: "上传成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: res.message,
      type: "warning",
    });
  }

  return false;
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

//新增一个测区
const addAreaOne = () => {
  reactiveData.areaList.push({
    name: "",
    regionName: "",
    address: "",
    area: "",
    areaFileList: [],
  });
};

const deleteAreaOne = (index: number) => {
  reactiveData.areaList.splice(index, 1);
};

//添加一条数据类型
const addTableOne = () => {
  reactiveData.dataTypeTable.push({
    type: "",
    typeCode: "",
    typeName: "",
    accuracy: "",
  });
};

//任务专题的过滤
const querySearch = (queryString: string, cb: Function) => {
  var arr: any[] = [];
  reactiveData.restaurants.forEach((item: string) => {
    if (item.indexOf(queryString) > -1) {
      arr.push({ value: item });
    }
  });
  cb(arr);
};

//获取所有行业
const getIndustryData = async () => {
  const res: any = await industryBelong({});
  if (res.statusCode === 200) {
    reactiveData.industryList = res.data;
  } else {
    reactiveData.industryList = [];
  }
};

//获取历史专题
const gethistorysubjectData = async (params: any) => {
  const res: any = await gethistorysubject(params);
  if (res.statusCode === 200) {
    reactiveData.restaurants = res.data;
  } else {
    reactiveData.restaurants = [];
  }
};

//获取所有历史专题
const getTaskTypeData = async (data: any) => {
  const res: any = await taskType(data);
  if (res.statusCode === 200) {
    reactiveData.taskTypeList = res.data;
  } else {
    reactiveData.taskTypeList = [];
  }
};

//获取所有数据类型
const getDataTypeData = async (data: any) => {
  const res: any = await taskType(data);
  if (res.statusCode === 200) {
    reactiveData.dataType = res.data;
  } else {
    reactiveData.dataType = [];
  }
};

const changeTypeData = (val: any, index: number, data: any) => {
  reactiveData.dataTypeTable[index].accuracy = "";
  reactiveData.dataTypeTable[index].type = val.type;
  reactiveData.dataTypeTable[index].typeCode = val.code;
  reactiveData.temporaryData = data;
  getAccuracyByDataType(val.id);
};

const deleteDataType = (index: number) => {
  reactiveData.dataTypeTable.splice(index, 1);
};

//根据数据类型获取精度
const getAccuracyByDataType = async (params: string) => {
  const res: any = await taskType({ parent: params });
  if (res.statusCode === 200) {
    reactiveData.temporaryData.accuracyList = res.data;
  } else {
    reactiveData.temporaryData.accuracyList = [];
  }
};

//获取对应的行政区县
const getAreaList = async (params: any) => {
  const res: any = await areaRegion(params);
  if (res.statusCode === 200) {
    reactiveData.areaBelongList = res.data;
  } else {
    reactiveData.areaBelongList = [];
  }
};

getIndustryData();
gethistorysubjectData({ type: "SJCJ" });
getTaskTypeData({ type: "tasktype", code: "SJCJ" });
getDataTypeData({ type: "DAQ" });
getAreaList({ city: "鹤壁市", level: 3 });
if (route && route.query.id) {
  id.value = route.query.id as string;
  getData(id.value);
}
</script>

<style lang='less'>
.info-page {
  height: 100%;
  width: 100%;
  .info-header {
    width: 98%;
    height: 30px;
    padding: 20px 1%;
    background: #f9fcff;
    box-shadow: 0px 0px 20px 5px #a5bbdc;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
    }
  }
  .info-detail {
    margin-top: 30px;
    width: 96%;
    height: 720px;
    padding: 20px 2%;
    background: #f9fcff;
    box-shadow: 0px 0px 20px 5px #a5bbdc;
    border-radius: 5px;
    .detail-header {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #488cff;
      display: flex;
      align-items: center;
      height: 60px;
      border-bottom: 1px solid #cccccc;
      margin-bottom: 30px;
      &::before {
        content: "";
        display: inline-block;
        width: 5px;
        height: 20px;
        margin-right: 10px;
        background: #488cff;
      }
    }
    .area-group {
      .area-item {
        padding-bottom: 30px;
        border-bottom: 1px solid #ccc;
        margin-bottom: 20px;
        .area-handle {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-right: 4%;
          margin-bottom: 10px;
          .area-label {
            text-align: center;
            width: 50px;
            padding: 8px 12px;
            font-size: 16px;
            background: #97adeb;
            font-weight: 600;
            color: #606266;
          }
        }
      }
    }
  }
}
</style>